package network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Microsoft
 * Date: 2023-08-03
 * Time: 17:05
 */
public class TcpEchoServer {
    private ServerSocket serverSocket = null;
    //serverSocket 就是外场拉客的小哥
    //clientSocket就是内场服务的小姐姐
    //serverSocket只有一个，clientSocket会给每个客户端都分配一个
    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        ExecutorService executorService = Executors.newCachedThreadPool();//线程池
        System.out.println("服务器启动");
        while (true) {//因为无时无刻不再接受请求，所以要使用true
            Socket clientSocket = serverSocket.accept();//就像serverSocket把顾客拉给了clientSocket
            //如果直接调用，该方法会影响这个循环的二次执行，导致accept不及时了
            //创建新的线程，用新线程来调用processConnection
            //每来一次新的客户端，都搞一个新的线程即可
///*            Thread t = new Thread(() -> {
//               try {
//                   processConnection(clientSocket);
//               } catch (IOException e) {
//                   e.printStackTrace();
//               }
//            });
//            t.start();//启动线程*/
            executorService.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

    //通过这个方法来处理一个连接
    //读取请求
    //根据请求计算响应
    //把相应返回给客户端
    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%d],客户端上线\n",clientSocket.getInetAddress().toString(),
                clientSocket.getPort());
        //try() 这种写法，（）中允许写多个流对象，使用;分号来进行分割
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()) {
            //没有这个scanner和printWriter，完全可以，但是代价就是得一个一个字节的扣，找到那个是请求结束的标记\n
            //不是不能做，而是比较麻烦
            //为了简单，把字节流包装成了更方便的字符流
            Scanner scanner = new Scanner(inputStream);//将字节流转换为了字符流
            PrintWriter printWriter = new PrintWriter(outputStream);
            while (true) {
                //1.读取请求
                if(!scanner.hasNext()) {
                    //说明读取的流到了结尾,对端关闭了
                    System.out.printf("[%s:%d],客户端下线\n",clientSocket.getInetAddress().toString(),
                            clientSocket.getPort());
                    break;
                }
                //直接使用scanner读取一段字符串
                String request = scanner.next();

                //2.根据请求计算响应
                String response = process(request);

                //3.把响应写回给客户端,不要忘了，响应里也是要带上换行的
                printWriter.println(response);
                printWriter.flush();
                System.out.printf("[%s:%d] req:%s; resp:%s\n",clientSocket.getInetAddress().toString(),
                        clientSocket.getPort(),request,response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            clientSocket.close();
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }

}



















